// Connection.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

#pragma comment(lib, "Winmm.lib") //for timeSetEvent

#define WM_MSG1 (WM_USER+100)
#define WM_MSG2 (WM_USER+101)
#define WM_MSG3 (WM_USER+102)
#define WM_EXIT (WM_USER+103)

static int s_mainthreadId = 0;

void CALLBACK TimeProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
{
	std::cout << "a SetTimer-timer comming" << std::endl;
	KillTimer(NULL, idTimer);
	PostMessage(NULL, WM_MSG2, 0, 0);
}

void CALLBACK MMTimeProc(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
{
	std::cout << "a timeSetEvent-timer comming" << std::endl;
	timeKillEvent(uTimerID);
	PostThreadMessage(s_mainthreadId, WM_MSG3, 0, 0);
}

int _tmain(int argc, _TCHAR* argv[])
{
	s_mainthreadId = GetCurrentThreadId();
	MSG msg;
	bool bExitFlag = false;
	PostMessage(NULL, WM_MSG1, 0, 0);
	while (!bExitFlag && GetMessage(&msg, NULL, 0, 0))
	{
		switch (msg.message)
		{
		case WM_TIMER:
			DispatchMessage(&msg);
			break;
		case WM_MSG1:
		{
			SetTimer(NULL, 1, 1000, TimeProc);
			break;
		}
		case WM_MSG2:
			std::cout << "receive message WM_MSG2" << std::endl;
			timeSetEvent(1000, 1, MMTimeProc, 0, TIME_PERIODIC);
			break;
		case WM_MSG3:
			std::cout << "receive message WM_MSG3" << std::endl;
			PostMessage(NULL, WM_EXIT, 0, 0);
			break;
		case WM_EXIT:
			std::cout << "receive message WM_EXIT" << std::endl;
			bExitFlag = true;
			break;
		default:
			std::cout << "receive other message" << std::endl;
			break;
		}
	}
	std::cout << "Press [Enter] to exit" << std::endl;
	getchar();
	return 0;
}